package com.example.traning.security.filter;

import cn.hutool.extra.servlet.JakartaServletUtil;
import com.example.traning.security.LoginUser;
import com.example.traning.security.util.SecurityUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.util.Objects;


/**
 * @author lei yu
 * @since 2024/10/14
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private final static String TOKEN_HEADER = "Authorization";

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {

        String actualToken = request.getHeader(TOKEN_HEADER);
        System.out.println("actualToken = " + actualToken);

        if (StringUtils.hasText(actualToken)) {
            String token = SecurityUtils.getToken();
            // 不通过
            if (!Objects.equals(token, actualToken)) {
                JakartaServletUtil.write(response, "访问令牌不匹配", MediaType.APPLICATION_JSON_UTF8_VALUE);
                return;
            }

            // 通过后，把用户信息存到上下文
            SecurityUtils.setLoginUser(new LoginUser(), request);
        }


        chain.doFilter(request, response);
    }
}
